package com.puboot.component;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Leonidax
 * @date 2024/9/27 14:03
 * @description FreeTranslateService
 */
@Component("freeTranslateService")
public class FreeTranslateService {
    private final int BLOCK=10000;
    @Value("${self.translate.token}")
    private String token;

    private final String CHINESE = "zh-Hans_CN";
    private final String CHINESE_T = "zh-Hant_TW";
    private final String ENGLISH = "en_GB";

    private HashMap<String,String> langMap;

    public FreeTranslateService(){
        langMap = new HashMap<>();
        langMap.put("fr","fr_FR");//法语
        langMap.put("en","en_GB");//英语
        langMap.put("es","es_ES");//西班牙语
        langMap.put("hi","hi_IN");//印地语
        langMap.put("ar","ar_EG");//阿拉伯语
        langMap.put("bn","bn_BD");//孟加拉语
        langMap.put("ru","ru_RU");//俄语
        langMap.put("id","id_ID");//印尼语
        langMap.put("pt","pt_PT");//葡萄牙语
    }

    public HashMap<String,String> getLangMap(){
        return langMap;
    }

    public String translate(String text, String lang){
        if(!langMap.containsKey(lang)) return null;
        if(text.length()<BLOCK) return translateContent(text, langMap.get(lang));
        StringBuilder content = new StringBuilder();
        //翻译CONTENT
        List<String> chunks = getChunks(text);

        for(String chunk:chunks){
            try{
                String result = translateContent(chunk, langMap.get(lang));
                content.append(result);
                content.append("\n");
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }
        return content.toString();
    }

    private String translateContent(String text, String lang){
        if(text == null || text.trim().equals("")) return null;
        String url = "https://api-b2b.backenster.com/b1/api/v3/translate/?client=site&feature=seo_text&lang_pair=en_te";

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

        // 设置表单数据
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("from", ENGLISH);
        formData.add("to", lang);
        formData.add("text", text);
        formData.add("platform", "dp");

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36");
        headers.set("Accept", "*/*");
        headers.set("Host", "api-b2b.backenster.com");
        headers.set("Connection", "keep-alive");
        headers.set("Authorization", token);

        // 封装请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, headers);
        try {
            // 发送POST请求并自动将响应体解析为Map
            ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, Map.class);

            // 从Map中提取result字段
            Map<String, String> responseBody = response.getBody();
            if (responseBody != null && responseBody.containsKey("result")) {
                return responseBody.get("result");
            } else {
                System.out.println(responseBody.get("err"));
                return null;
            }
        }catch (Exception e){
            System.out.println("Error:======="+e.getMessage());
            return null;
        }
    }


    /**
     * 顺便过滤掉多余的空格和换行符
     * @param text
     * @return
     */
    private List<String> getChunks(String text) {
        List<String> chunks = new ArrayList<>();
        String splitChar = "\n";
        String[] lines = text.split(splitChar);
        int limit = 0;
        int length;
        String chunk = "";
        for(String line : lines){
            line = line.trim();
            line += "\n";
            length = line.length();
            if(limit+length>BLOCK){
                chunks.add(chunk);
                limit = length;
                chunk = line;
            }else{
                limit += length;
                chunk += line;
            }
        }
        chunks.add(chunk);
        return chunks;
    }
}
